<?php

if ( 'on' == get_site_option( 'bpdev-widgets-status' ) )
	add_action( 'widgets_init', 'bpdev_widgets_profile_friends_of_you_init' );
elseif ( !function_exists( 'bpdev_widgets_setup_globals' ) )
	add_action( 'widgets_init', 'bpdev_widgets_profile_friends_of_you_init' );

function bpdev_widgets_profile_friends_of_you_init() {

	global $bp;

	function bpdev_widgets_profile_friends_of_you_show( $args ) {

		global $bp;
		extract($args);
		$friend_ids = BP_Friends_Friendship::get_random_friends( $bp->displayed_user->id , 28 );

		if ( !bp_is_home() && $bp->loggedin_user->id && $bp->loggedin_user->id != 0 ) {

			?>

			<?php echo $before_widget ?>
				<?php echo $before_title ?><?php bp_word_or_name( __( "Common friends", 'buddypress' ), __( "Common friends", 'buddypress' ) ) ?><?php echo $after_title ?>
				
				<?php if ( $friend_ids ) { ?>

					<ul class="bpdev-widgets profile-widget bpdev-widget-avatar-list" id="bpdev-profile-friends-of-you">

					<?php 

					$count = 0;
					for ( $i = 0; $i < count( $friend_ids ); $i++ ) {
						if ( 'is_friend' == BP_Friends_Friendship::check_is_friend( $bp->loggedin_user->id, $friend_ids[$i] )  ) :

							$count = $count + 1;
							?>

						<li>
							<a href="<?php echo bp_core_get_userurl( $friend_ids[$i] ) ?>"><?php echo bp_core_get_avatar( $friend_ids[$i], 1, 30, 30 ) ?></a>
						</li>

					<?php endif;

					}

					if ( $count == 0 ) {

						?>

						<div id="message" class="info">
							<p><?php bp_word_or_name( __( "You haven't added any friend connections yet.", 'buddypress' ), __( "%s hasn't created any friend connections yet.", 'buddypress' ) ) ?></p>
						</div>

						<?php

					}

					?>

					</ul>

				<?php } else { ?>

					<div id="message" class="info">
						<p><?php bp_word_or_name( __( "You haven't added any friend connections yet.", 'buddypress' ), __( "%s hasn't created any friend connections yet.", 'buddypress' ) ) ?></p>
					</div>

				<?php } ?>

				<div class="clear"></div>
			<?php echo $after_widget; ?>

			<?php

		}

	}

	register_sidebar_widget( 'BPDEV Friends Of You', 'bpdev_widgets_profile_friends_of_you_show' );

}
?>